<template>
  <div>
    <van-nav-bar title="订单确认" left-arrow :fixed="true" :z-index="9" :border="false" style="background-color: #f44;height: 50px;" @click-left="onClickLeft"/>
    <!--收货地址选择-->
    <AddressCard ref="addressCard" style="margin-top: 51px;" :editable="true"></AddressCard>
    <!--订单中商品展示-->
    <div v-for="item in itemList" :key="item.id">
      <van-card :title="item.itemName" :desc="item.description" :price="formatPrice(item.salePrice)" :thumb="item.itemPic.split('###')[0]" @click-thumb="toDetail(item)">
        <div slot="tags">
          规格：{{ item.itemGg }}
        </div>
        <div slot="bottom" style="float: left">
          共{{ item.buyNum }}件&nbsp;小计：<span style="color: red">{{ formatPrice(item.salePrice * item.buyNum) }}</span>
        </div>
      </van-card>
    </div>
    <div>
      <van-cell-group>
        <van-field v-model="remark" type="textarea" left-icon="comment" placeholder="请输入订单备注" autosize/>
      </van-cell-group>
    </div>
    <!--提交订单-->
    <van-submit-bar :loading="submitLoading" :label="leftLabel" :price="totalPrice" button-text="提交订单" @submit="onSubmit" style="height: 55px;"/>
  </div>
</template>

<script>
import AddressCard from '@/components/AddressCard'
export default {
  name: 'placeOrder',
  components: {
    AddressCard
  },
  data () {
    return {
      ids: '', // 待结算商品id
      itemList: [], // 商品列表
      totalNum: 0, // 总件数
      buyNum: 0, // 购买件数（直接购买时，将购物件数传输至此）
      leftLabel: '', // 价格左侧label
      totalPrice: 0, // 总价格
      remark: '', // 订单备注
      submitLoading: false
    }
  },
  methods: {
    /**
     * 根据当前时间和随机数生成流水号
     */
    getOrderNumber (val) {
      let orderNumber = ''
      const now = new Date()
      let year = now.getFullYear() // 年
      let month = now.getMonth() + 1 // 月
      let day = now.getDate() // 日
      let hour = now.getHours() // 时
      let minutes = now.getMinutes() // 分
      let seconds = now.getSeconds() // 秒
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      if (hour < 10) {
        hour = '0' + hour
      }
      if (minutes < 10) {
        minutes = '0' + minutes
      }
      if (seconds < 10) {
        seconds = '0' + seconds
      }
      orderNumber = val + year + month + day + hour + minutes + seconds
      return orderNumber + (Math.round(Math.random() * 23 + 100)).toString()
    },
    /**
     * 返回
     */
    onClickLeft () {
      this.$router.go(-1)
    },
    /**
     * 价格格式化
     */
    formatPrice (price) {
      return (price * 100 / 100).toFixed(2)
    },
    /**
     * 查看商品详情
     */
    toDetail (item) {
      this.$router.push({ name: 'detail', query: { itemId: item.itemId } })
    },
    getItemListFromCartByCartId (ids) {
      const self = this
      self.submitLoading = true
      const param = { ids: ids }
      self.axios.get('api/shop/getItemListFromCartByCartId', { params: param }).then(resp => {
        if (resp.data.code !== '-1') {
          self.itemList = resp.data.data
          resp.data.data.forEach(item => {
            this.totalNum += Number(item.buyNum)
            this.totalPrice += Number(item.salePrice * item.buyNum)
          })
          this.leftLabel = '共' + this.totalNum + '件，合计：'
          this.totalPrice = this.totalPrice * 100
          self.submitLoading = false
        } else {
          self.$toast(resp.data.msg)
          self.submitLoading = false
        }
      }).catch(error => {
        console.log(error)
        self.submitLoading = false
      })
    },
    /**
     * 根据商品id查询商品信息
     */
    getItemByItemId (itemId) {
      const self = this
      self.submitLoading = true
      const param = { itemId: itemId }
      self.axios.get('api/shop/getItemByItemId', { params: param }).then(resp => {
        if (resp.data.code !== '-1') {
          // 购买件数
          let buyNum = self.$route.query.buyNum
          resp.data.data.buyNum = buyNum
          resp.data.data.itemId = itemId
          self.itemList.push(resp.data.data)
          this.totalNum = Number(buyNum)
          this.totalPrice = Number(resp.data.data.salePrice * buyNum)
          this.leftLabel = '共' + this.totalNum + '件，合计：'
          this.totalPrice = this.totalPrice * 100
          self.submitLoading = false
        } else {
          self.$toast(resp.data.msg)
          self.submitLoading = false
        }
      }).catch(error => {
        console.log(error)
        self.submitLoading = false
      })
    },
    /**
     * 提交订单
     */
    onSubmit () {
      const self = this
      // 选中的地址id
      let addressId = self.$refs.addressCard.chosenAddressId
      if (addressId !== undefined && addressId !== '') {
        self.submitLoading = true
        // 订单主表信息
        let orderInfo = {}
        // 订单号生成
        let orderNo = self.getOrderNumber('XS')

        orderInfo.openId = self.$store.state.openId
        orderInfo.orderNo = orderNo
        orderInfo.addressId = addressId
        orderInfo.totalNum = self.totalNum
        orderInfo.totalFee = self.totalPrice / 100 // 分换算元
        orderInfo.payWay = ''
        orderInfo.remark = self.remark
        const param = {
          order: orderInfo,
          orderDetail: self.itemList,
          ids: self.ids
        }
        self.axios.post('api/shop/addShopOrder', param).then(resp => {
          if (resp.data.code !== '-1') {
            self.$toast('提交成功')
            this.$router.push({ name: 'orderList', params: { active: '1' } })
            setTimeout(function () {
              self.submitLoading = false
            }, 2000)
          } else {
            self.$toast(resp.data.msg)
            setTimeout(function () {
              self.submitLoading = false
            }, 2000)
          }
        }).catch(error => {
          setTimeout(function () {
            self.submitLoading = false
          }, 2000)
          console.log(error)
        })
      } else {
        self.$toast('请选择收货地址~')
      }
    }
  },
  mounted () {
    const self = this
    // 结算类型 1：购物车结算 2：直接结算
    let payType = self.$route.query.payType
    if (payType === '1') {
      // 获取购物车ids
      let ids = self.$route.query.ids
      self.ids = ids
      self.getItemListFromCartByCartId(ids)
    } else {
      // 获取商品id
      let itemId = self.$route.query.itemId
      self.ids = itemId
      self.getItemByItemId(itemId)
    }
  }
}
</script>

<style lang="less" scoped>
.van-nav-bar .van-icon {
  color: white;
  vertical-align: middle;
}

.van-nav-bar__title {
  color: white;
}

.van-card__content {
  text-align: left;
}

.van-card__price {
  width: 80%;
  color: black;
}
</style>
